package com.nenglai.common.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kongdehui
 * @date 2021/05/17 13:49
 **/
@Slf4j
public class Map2Object {

    public static Map<String, String> convert(Object o) {
        Map<String, String> map = new HashMap<>();
        Field[] fields = o.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Map2ObjectKey map2ObjectKey = field.getAnnotation(Map2ObjectKey.class);
                String key = "";
                if (map2ObjectKey != null) {
                    key = map2ObjectKey.value();
                } else {
                    key = field.getName();
                }
                String value = field.get(o) != null ? field.get(o).toString() : "";
                map.put(key, value);
            }
        } catch (SecurityException | IllegalAccessException e) {
            log.debug("map2object error:{}", e.getMessage());
        }
        return map;
    }
}
